package com.zengqingfa.designpattern.structure.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 *
 * @fileName: RealProxy
 * @author: zengqf3
 * @date: 2021-4-22 8:49
 * @description:
 */
public class CGLibProxy implements MethodInterceptor {

    private Object target;

    public Object createProxyObject(Object obj) {
        this.target = obj;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        Object proxyObj = enhancer.create();
        // 返回代理对象
        return proxyObj;
    }

    /**
     *
     * @param proxy "this", the enhanced object
     * @param method intercepted Method
     * @param args argument array; primitive types are wrapped
     * @param proxy used to invoke super (non-intercepted method); may be called
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("start....");
        Object obj = method.invoke(target, args);
        System.out.println("end....");
        return obj;
    }
}
